package messangerTypes;

import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.ObjectInput;
import java.io.ObjectInputStream;
import java.io.ObjectOutput;
import java.io.ObjectOutputStream;

@SuppressWarnings("serial")
public class MessageBase implements java.io.Serializable
{
	public static enum MessageType {NULL, MULTICAST_ANOUNCMENT, USER_MESSAGE, CONNECT_REQUEST, CONNECT_RESPONSE, KEEP_ALIVE};
	protected MessageType type = MessageType.NULL;
	
	public MessageBase(MessageType type)
	{
		this.type = type;
	}
	
	public MessageType getType()
	{
		return type;
	}

	public static MessageBase createObjectFromBytes (byte[] bytes)
	{
		ByteArrayInputStream bis = new ByteArrayInputStream(bytes);
		ObjectInput in = null;
		MessageBase returnVal = null;
		try 
		{
			in = new ObjectInputStream(bis);
			returnVal = (MessageBase)in.readObject(); 
		} 
		catch (IOException e)
		{
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		catch (ClassNotFoundException e)
		{
			// TODO Auto-generated catch block
			e.printStackTrace();
		} 
		finally 
		{
			try 
			{
				bis.close();
			} 
			catch (IOException ex) 
			{
				// ignore close exception
			}
			try
			{
				if (in != null) 
				{
					in.close();
				}
			} 
			catch (IOException ex) 
			{
				// ignore close exception
			}
		}
		return returnVal;
	}
	
	public byte[] getBytes ()
	{
		ByteArrayOutputStream bos = new ByteArrayOutputStream();
		ObjectOutput out = null;
		byte[] buffer = null;
		
		try 
		{
		  out = new ObjectOutputStream(bos);   
		  out.writeObject(this);
		  buffer = bos.toByteArray();
		  
		} catch (IOException e)
		{
			e.printStackTrace();
		} 
		finally 
		{
			try
			{ 
				out.close();
				bos.close();
			} 
			catch (IOException e)
			{
				e.printStackTrace();
			}
		}
		return buffer;
	}

}
